package test.print;

import java.io.FileInputStream;
import java.io.IOException;

import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintException;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.Copies;
import javax.print.attribute.standard.MediaSizeName;

public class PrintEx {
	static public void main(String args[]) throws Exception {
		
		printTest2();
	}

	public static void printTest1() {
		try {
			PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
			pras.add(new Copies(1));

			//PrintService pss[] = PrintServiceLookup.lookupPrintServices(DocFlavor.INPUT_STREAM.PDF, pras);
			PrintService pss[] = PrintServiceLookup.lookupPrintServices(null, pras);

			if (pss.length == 0)
				throw new RuntimeException("No printer services available.");

			PrintService ps = pss[0];
			System.out.println("Printing to " + ps);

			DocPrintJob job = ps.createPrintJob();

//			String filename = "c:/sample.pdf";
//			String filename = "c:/test.txt";
			String filename = "c:/images/vitech1.tif";
			FileInputStream fin = new FileInputStream(filename);
			Doc doc = new SimpleDoc(fin, DocFlavor.INPUT_STREAM.GIF, null);

			job.print(doc, pras);
			System.out.println("Printed " + filename);

			fin.close();
		} catch (IOException ie) {
			ie.printStackTrace();
		} catch (PrintException pe) {
			pe.printStackTrace();
		}
	}
	
	public static void printTest2() throws Exception {
		DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
		PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
		aset.add(MediaSizeName.ISO_A4);
		PrintService[] pservices =
			PrintServiceLookup.lookupPrintServices(flavor, aset);
		if (pservices.length > 0) {
			DocPrintJob pj = pservices[0].createPrintJob();
			String filename = "c:/sample.pdf";
			FileInputStream fin = new FileInputStream(filename);
			Doc doc = new SimpleDoc(fin, flavor, null);
			try {
				pj.print(doc, aset);
				System.out.println("Printed " + filename);
			} catch (PrintException e) { 
			} finally {
				fin.close();
			}			
		}

	}
}
